import Router from '@koa/router';
import response from '../response.js';
import AdmZip from 'adm-zip';
import fs from 'fs'
import fse from 'fs-extra'
import path from 'path'
import { dir } from 'console';

const router = new Router();
router.prefix('/api');



async function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

//上传前端zip文件并解压到软件根目录下View文件夹
router.post('/sys/upload', async (ctx) => {
    try {
        let file = ctx.request.files.file;
        if (!file) {
            ctx.body = response.error('No file uploaded');
            return;
        }
        //检查文件扩展名是否为zip
        if (file.mimetype != 'application/zip') {
            ctx.body = response.error('File type error');
            return;
        }
        let targetDir = './View';
        if(ctx.request.body.path != undefined){
            targetDir = targetDir + '/' + ctx.request.body.path;
        }
        //把上传的文件保存到软件根目录下
        let reader = fs.createReadStream(file.filepath);
        let filePath = '';
        let filename = ctx.request.body.filename;
        if (filename == undefined) {
            filename = file.originalFilename;
        }
        filePath = path.join('./', filename);
        let upStream = fs.createWriteStream(filePath);
        reader.pipe(upStream);

        //等待文件写入完成
        await new Promise((resolve, reject) => {
            upStream.on('finish', resolve);
            upStream.on('error', reject);
        });

        //解压zip文件到软件根目录下View文件夹
        let zip = new AdmZip(filePath);
        zip.extractAllTo('./dist', true);
        //删除上传的zip文件
        fs.unlinkSync(filePath);

        //检查./dest文件夹是否存在
        let  dirPath = './dist/dist';
     
        // 检查 dirPath 是否存在
        if (fs.existsSync(dirPath)) {
            // 检查 targetDir 是否存在，如果不存在则创建
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }
            // 获取 dirPath 下的所有文件
            const files = fs.readdirSync(dirPath);
            // 移动文件到 targetDir
            files.forEach(file => {
                const srcPath = path.join(dirPath, file);
                const destPath = path.join(targetDir, file);
                fse.moveSync(srcPath, destPath, { overwrite: true });
            });
            //删除dist文件夹
            fse.removeSync(dirPath);


            console.log('Files moved successfully.');
        } else {
            dirPath = './dist';
            if (fs.existsSync(dirPath)) {
                // 检查 targetDir 是否存在，如果不存在则创建
                if (!fs.existsSync(targetDir)) {
                    fs.mkdirSync(targetDir, { recursive: true });
                }
                // 获取 dirPath 下的所有文件
                const files = fs.readdirSync(dirPath);
                // 移动文件到 targetDir
                files.forEach(file => {
                    const srcPath = path.join(dirPath, file);
                    const destPath = path.join(targetDir, file);
                    fse.moveSync(srcPath, destPath, { overwrite: true });
                });
                //删除dist文件夹
                fse.removeSync(dirPath);
    
    
                console.log('Files moved successfully.');
            }else{
                ctx.body = response.fail('解压后未发现dist文件夹');
                return;
            }
        }

        ctx.body = response.success();
    } catch (err) {
        console.log('file upload failed', err.message);
        ctx.body = response.fail('File upload failed');
    }
}
);

//重启整个服务的接口
router.post('/sys/restart', async (ctx) => {
    let body = ctx.request.body;
    //重启整个服务
    if(body.password != '123456'){
        ctx.body = response.fail('密码错误');
        return;
    }
    console.log('soft reveice reboot command  will restart in 1s');
    setTimeout(() => {
        process.exit(0);
    }, 1000);
    ctx.body = response.success();
});



router.post('/file/upload', async (ctx) => {
    try {
        let file = ctx.request.files.file;
        if (!file) {
            ctx.body = response.error('No file uploaded');
            return;
        }
        //检查文件扩展名是否为zip
        // const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif'];
        // if (!allowedImageTypes.includes(file.mimetype)) {
        //     ctx.body = response.error('File type error');
        //     return;
        // }
        //把上传的文件保存到软件根目录下
        let reader = fs.createReadStream(file.filepath);
        let filePath = '';
        let filename = ctx.request.body.filename;
        if (filename == undefined) {
            filename = file.originalFilename;
        }
        filePath = path.join('./View', filename);
        let upStream = fs.createWriteStream(filePath);
        reader.pipe(upStream);

        //等待文件写入完成
        await new Promise((resolve, reject) => {
            upStream.on('finish', resolve);
            upStream.on('error', reject);
        });

        
        ctx.body = response.success();
    } catch (err) {
        console.log('file upload failed', err.message);
        ctx.body = response.fail('File upload failed');
    }
}
);

export { router };
